<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Asset extends MX_Controller {
    
  function __construct() {
    $this->load->library('manimage');
    $this->load->model('frm/mfrm');
    $this->menu = $this->cek();
  }
	
	public function kegiatan_inday($id_mrp_inventory_department, $tanggal){
    $data = $this->global_models->get_query("
      SELECT A.*
      FROM mrp_history_inventory AS A
      WHERE A.id_mrp_inventory_department = $id_mrp_inventory_department AND
        ('".  str_replace("_", "-", $tanggal)."' BETWEEN A.tanggal AND A.finish)
      ORDER BY A.timein ASC
      ");
    print "<ul>";
    foreach($data AS $dt){
      print "<li>
        Title : {$dt->title} <br />
        Date : {$dt->tanggal} {$dt->timein} - {$dt->finish} {$dt->timeout} <br />
        PIC : {$dt->pic} <br />
        Note : {$dt->note}
        </li>";
    }
    print "</ul>";
//    $this->debug($data, true);
    die;
  }
	public function add_inventory_department($id_hrm_department, $id_mrp_inventory_department = 0){
    $detail = $this->global_models->get_query("
        SELECT A.*, B.title AS mrp_inventory
        FROM mrp_inventory_department AS A
        LEFT JOIN mrp_inventory AS B ON A.id_mrp_inventory = B.id_mrp_inventory
        WHERE A.id_mrp_inventory_department = $id_mrp_inventory_department
        ");
    if($this->input->post()){
      $pst = $this->input->post();
      if($pst['id_detail']){
        $kirim = array(
            'sn'                  => $pst['sn'],
            'id_hrm_department'   => $id_hrm_department,
            'id_mrp_inventory'    => $pst['id_mrp_inventory'],
            'tanggal'             => $pst['tanggal'],
            'guarantee'           => $pst['guarantee'],
            'expired'             => $pst['expired'],
            'pi'                  => $pst['pi'],
            'nilai_awal'          => $this->global_models->string_to_number($pst['nilai_awal']),
            'nilai_akhir'         => $this->global_models->string_to_number($pst['nilai_akhir']),
            'umur_ekonomis'       => $pst['umur_ekonomis'],
            'note'                => $pst['note'],
	          'update_by_users' =>  $this->session->userdata("id"),
        );
        $id_mrp_inventory_department = $this->global_models->update("mrp_inventory_department", array("id_mrp_inventory_department"=> $pst['id_detail']), $kirim);
      }
      else{
        $kirim = array(
            'sn'                  => $pst['sn'],
            'id_hrm_department'   => $id_hrm_department,
            'id_mrp_inventory'    => $pst['id_mrp_inventory'],
            'tanggal'             => $pst['tanggal'],
            'guarantee'           => $pst['guarantee'],
            'expired'             => $pst['expired'],
            'pi'                  => $pst['pi'],
            'nilai_awal'          => $this->global_models->string_to_number($pst['nilai_awal']),
            'nilai_akhir'         => $this->global_models->string_to_number($pst['nilai_akhir']),
            'umur_ekonomis'       => $pst['umur_ekonomis'],
            'note'                => $pst['note'],
	          'create_by_users' =>  $this->session->userdata("id"),
            'create_date'     =>  date("Y-m-d H:i:s")
        );
        $id_mrp_inventory_department = $this->global_models->insert("mrp_inventory_department", $kirim);
      }
      if($id_mrp_inventory_department){
        $this->session->set_flashdata('success', 'Data tersimpan');
      }
      else{
        $this->session->set_flashdata('notice', 'Data tidak tersimpan');
      }
      redirect("mrp/asset/history-inventory/$id_hrm_department/{$detail[0]->id_mrp_inventory}");
    }
    else{
//      $this->debug($detail, true);
      $this->template->build("asset/add-inventory-department",
        array(
              'url'         => base_url()."themes/".DEFAULTTHEMES."/",
              'menu'        => 'mrp/asset/department',
              'title'       => lang("inventory"),
              'detail'      => $detail,
            ));
      $this->template
        ->set_layout('default')
        ->build("asset/add-inventory-department");
    }
  }
  
	public function add_history_inventory($id_mrp_inventory_department, $id_history_inventory= 0){
    $inventory_department = $this->global_models->get("mrp_inventory_department", array("id_mrp_inventory_department" => $id_mrp_inventory_department));
    if($this->input->post()){
      $pst = $this->input->post();
//      $this->debug($pst, true);
      if($pst['id_detail']){
        $kirim = array(
            'title'           => $pst['title'],
            'tanggal'         => $pst['tanggal'],
            'timein'          => $pst['timein'],
            'tanggalin'       => $pst['tanggal']." ".$pst['timein'],
            'finish'          => $pst['finish'],
            'timeout'         => $pst['timeout'],
            'tanggalout'      => $pst['finish']." ".$pst['timeout'],
            'id_mrp_inventory_department' => $id_mrp_inventory_department,
            'pic'             => $pst['pic'],
            'status'          => $pst['status'],
            'note'            => $pst['note'],
	          'update_by_users' =>  $this->session->userdata("id"),
        );
        $id_mrp_history_inventory = $this->global_models->update("mrp_history_inventory", array("id_mrp_history_inventory"=> $pst['id_detail']), $kirim);
      }
      else{
        $kirim = array(
            'title'           => $pst['title'],
            'tanggal'         => $pst['tanggal'],
            'timein'          => $pst['timein'],
            'tanggalin'       => $pst['tanggal']." ".$pst['timein'],
            'finish'          => $pst['finish'],
            'timeout'         => $pst['timeout'],
            'tanggalout'      => $pst['finish']." ".$pst['timeout'],
            'id_mrp_inventory_department' => $id_mrp_inventory_department,
            'pic'             => $pst['pic'],
            'status'          => $pst['status'],
            'note'            => $pst['note'],
	          'create_by_users' => $this->session->userdata("id"),
            'create_date'     => date("Y-m-d H:i:s")
        );
        $id_mrp_history_inventory = $this->global_models->insert("mrp_history_inventory", $kirim);
      }
      if($id_mrp_history_inventory){
        $data_akhir = $this->global_models->get_query("
          SELECT *
          FROM mrp_history_inventory
          WHERE id_mrp_inventory_department = $id_mrp_inventory_department
          ORDER BY tanggal DESC LIMIT 0,1
          ");
        if($data_akhir[0]->status)
          $sts = 2;
        else
          $sts = 1;
        $this->global_models->update("mrp_inventory_department", array("id_mrp_inventory_department" => $id_mrp_inventory_department), 
                array('pic'   => $data_akhir[0]->pic, 'status' => $sts));
        redirect("mrp/asset/history-inventory/{$inventory_department[0]->id_mrp_inventory}/$id_mrp_inventory_department/1/Berhasil");
      }
      else{
        redirect("mrp/asset/history-inventory/{$inventory_department[0]->id_mrp_inventory}/$id_mrp_inventory_department/2/Gagal");
      }
    }
    else{
      $data = $this->global_models->get("mrp_history_inventory", array("id_mrp_history_inventory" => $id_history_inventory));
      $this->template->build("asset/add-history-inventory",
        array(
              'url'         => base_url()."themes/".DEFAULTTHEMES."/",
              'menu'        => 'mrp/asset/department',
              'title'       => lang("inventory"),
              'detail'      => $data
            ));
      $this->template
        ->set_layout('default')
        ->build("asset/add-history-inventory");
    }
  }
  
	public function add_booking($id_mrp_inventory_booking = 0){
    $data = $this->global_models->get("mrp_inventory_booking", array("id_mrp_inventory_booking" => $id_mrp_inventory_booking));
    if($this->input->post()){
      $pst = $this->input->post();
//      $this->debug($pst, true);
      if($pst['id_detail']){
        $kirim = array(
            'title'           => $pst['title'],
            'tanggal'         => $pst['tanggal'],
            'timein'          => $pst['timein'],
            'tanggalin'       => $pst['tanggal']." ".$pst['timein'],
            'finish'          => $pst['finish'],
            'timeout'         => $pst['timeout'],
            'tanggalout'      => $pst['finish']." ".$pst['timeout'],
            'id_mrp_inventory_department' => $pst['id_mrp_inventory_department'],
            'id_hrm_department' => $pst['id_hrm_department'],
            'pic'             => $pst['pic'],
            'price'           => $this->global_models->string_to_number($pst['price']),
            'notransaksi'     => $pst['notransaksi'],
            'note'            => $pst['note'],
            'status'          => $pst['status'],
	          'update_by_users' =>  $this->session->userdata("id"),
        );
        $id_mrp_inventory_booking = $this->global_models->update("mrp_inventory_booking", array("id_mrp_inventory_booking"=> $pst['id_detail']), $kirim);
        if($pst['status'] == 2 AND $data[0]->status != 2){
          
          unset($kirim['id_hrm_department']);
          $id_mrp_history_inventory = $this->global_models->insert("mrp_history_inventory", $kirim);
          
//          set journal
          if($this->global_models->string_to_number($pst['price']) > 0){
            $id_piutang_pendapataan_asset = $this->nbscache->get_explode("variable", "id_piutang_pendapataan_asset");
            $id_pendapatan_asset = $this->nbscache->get_explode("variable", "id_pendapatan_asset");
            
            $kirim_purchase = array(
                'id_mrp_inventory_booking'    => $pst['id_detail'],
                'id_frm_account'              => $id_pendapatan_asset[1],
                'notransaksi'                 => $pst['notransaksi'],
                'saldo'                       => $this->global_models->string_to_number($pst['price']),
                'pos'                         => 2,
                'note'                        => $pst['note'],
                'create_by_users'             => $this->session->userdata("id"),
                'create_date'                 => date("Y-m-d H:i:s")
            );
            
            $id_mrp_inventory_payment_booking = $this->global_models->insert("mrp_inventory_payment_booking", $kirim_purchase);
            
            $kirim_journal = array(
                "id_frm_journal"      => $this->mfrm->get_journal_current(),
                "notransaksi"         => $pst['notransaksi'],
                "saldo"               => $this->global_models->string_to_number($pst['price']),
                "tanggal"             => date("Y-m-d"),
                "note"                => "Pendapatan Penggunaan Asset <a href='".site_url("mrp/asset/payment-booking/".$pst['id_detail'])."'>".$pst['title']."</a>",
            );

            $id_frm_journal_log = $this->mfrm->create_journal_log($kirim_journal);
            
            if($id_frm_journal_log){
              $debit[] = $this->global_models->string_to_number($pst['price']);
              $debit_da[] = $id_piutang_pendapataan_asset[1];

              $kredit[] = $this->global_models->string_to_number($pst['price']);
              $kredit_da[] = $id_pendapatan_asset[1];
              $this->mfrm->create_journal_log_account($this->mfrm->get_journal_current(), $id_frm_journal_log, $debit, $debit_da, $kredit, $kredit_da);
            }
          }
          
        }
      }
      else{
        $kirim = array(
            'title'           => $pst['title'],
            'tanggal'         => $pst['tanggal'],
            'timein'          => $pst['timein'],
            'tanggalin'       => $pst['tanggal']." ".$pst['timein'],
            'finish'          => $pst['finish'],
            'timeout'         => $pst['timeout'],
            'tanggalout'      => $pst['finish']." ".$pst['timeout'],
            'id_mrp_inventory_department' => $pst['id_mrp_inventory_department'],
            'id_hrm_department' => $pst['id_hrm_department'],
            'pic'             => $pst['pic'],
            'price'           => $this->global_models->string_to_number($pst['price']),
            'notransaksi'     => $pst['notransaksi'],
            'status'          => 1,
            'note'            => $pst['note'],
	          'create_by_users' => $this->session->userdata("id"),
            'create_date'     => date("Y-m-d H:i:s")
        );
        $id_mrp_inventory_booking = $this->global_models->insert("mrp_inventory_booking", $kirim);
      }
      if($id_mrp_inventory_booking){
        redirect("mrp/asset/booking/1/Berhasil");
      }
      else{
        redirect("mrp/asset/booking/2/Gagal");
      }
    }
    else{
      $department = $this->global_models->get_dropdown("hrm_department", "id_hrm_department", "title", false);
      if(!$data[0]->id_hrm_department){
        foreach ($department as $kdp => $dptm){
          $inventory = $this->global_models->get_query("
            SELECT A.*, B.title AS inventory
            FROM mrp_inventory_department AS A
            LEFT JOIN mrp_inventory AS B ON A.id_mrp_inventory = B.id_mrp_inventory
            WHERE A.id_hrm_department	= $kdp
            ");
          break; 
        }
      }
      else{
        $inventory = $this->global_models->get_query("
          SELECT A.*, B.title AS inventory
          FROM mrp_inventory_department AS A
          LEFT JOIN mrp_inventory AS B ON A.id_mrp_inventory = B.id_mrp_inventory
          WHERE A.id_hrm_department	= {$data[0]->id_hrm_department}
          ");
      }
      foreach ($inventory AS $inv){
        $inventory_dropdown[$inv->id_mrp_inventory_department] = $inv->inventory."-".$inv->sn;
      }
//      $this->debug($data[0]->id_hrm_department, true);
      $this->template->build("asset/add-asset-booking",
        array(
              'url'         => base_url()."themes/".DEFAULTTHEMES."/",
              'menu'        => 'mrp/asset/department',
              'title'       => lang("asset_booking"),
              'detail'      => $data,
              'department'  => $department,
              'inventory'   => $inventory_dropdown,
            ));
      $this->template
        ->set_layout('default')
        ->build("asset/add-asset-booking");
    }
  }
  
	public function add_history_penyusutan($id_mrp_inventory_department, $id_mrp_inventory_penyusutan = 0){
    $inv_department = $this->global_models->get("mrp_inventory_department", array("id_mrp_inventory_department" => $id_mrp_inventory_department));
    if($this->input->post()){
      $pst = $this->input->post();
//      $this->debug($pst, true);
      if($pst['id_detail']){
        $kirim = array(
            'title'           => $pst['title'],
            'tanggal'         => $pst['tanggal'],
            'nilai'           => ($this->global_models->string_to_number($pst['nilai']) * -1),
            'notransaksi'     => $pst['notransaksi'],
            'id_mrp_inventory_department' => $id_mrp_inventory_department,
            'note'            => $pst['note'],
	          'create_by_users' => $this->session->userdata("id"),
            'create_date'     => date("Y-m-d H:i:s")
        );
        $id_mrp_inventory_penyusutan = $this->global_models->update("mrp_inventory_penyusutan", array("id_mrp_inventory_penyusutan" => $pst['id_detail']), $kirim);
      }
      else{
        $kirim = array(
            'title'           => $pst['title'],
            'tanggal'         => $pst['tanggal'],
            'nilai'           => ($this->global_models->string_to_number($pst['nilai']) * -1),
            'notransaksi'     => $pst['notransaksi'],
            'id_mrp_inventory_department' => $id_mrp_inventory_department,
            'note'            => $pst['note'],
	          'create_by_users' => $this->session->userdata("id"),
            'create_date'     => date("Y-m-d H:i:s")
        );
        $id_mrp_inventory_penyusutan = $this->global_models->insert("mrp_inventory_penyusutan", $kirim);
      }
      if($id_mrp_inventory_penyusutan){
        $this->session->set_flashdata('success', 'Data tersimpan');
      }
      else{
        $this->session->set_flashdata('notice', 'Data tidak tersimpan');
      }
      redirect("mrp/asset/history-inventory/".$inv_department[0]->id_hrm_department."/".$inv_department[0]->id_mrp_inventory."/".$inv_department[0]->id_mrp_inventory_department);
    }
    else{
      
      $this->template->build("asset/add-history-penyusutan",
        array(
              'url'         => base_url()."themes/".DEFAULTTHEMES."/",
              'menu'        => 'mrp/asset/department',
              'title'       => lang("mrp_history_penyusutan"),
            ));
      $this->template
        ->set_layout('default')
        ->build("asset/add-history-penyusutan");
    }
  }
  
	public function add_purchase($id_mrp_inventory_purchase = 0){
    $data = $this->global_models->get("mrp_inventory_purchase", array("id_mrp_inventory_purchase" => $id_mrp_inventory_purchase));
    if($this->input->post()){
      $pst = $this->input->post();
//      $this->debug($pst, true);
      if($pst['id_detail']){
        if($pst['status'] == 2 AND $this->global_models->get_field("mrp_inventory_purchase", "status", array("id_mrp_inventory_purchase" => $pst['id_detail'])) < 2){
          $accept = true;
        }
        else{
          $accept = false;
        }
        
        if($pst['status'] == 4 AND $this->global_models->get_field("mrp_inventory_purchase", "status", array("id_mrp_inventory_purchase" => $pst['id_detail'])) < 4){
          $item_purchase = $this->global_models->get("mrp_inventory_purchase_items", array("id_mrp_inventory_purchase" => $id_mrp_inventory_purchase));
          foreach($item_purchase as $ip){
            for($g = 0 ; $g < $ip->qty ; $g++){
              $kirim_inventory = array(
                  'id_hrm_department'   => $data[0]->id_hrm_department,
                  'id_mrp_inventory'    => $ip->id_mrp_inventory,
                  'id_mrp_inventory_purchase' => $id_mrp_inventory_purchase,
                  'tanggal'             => date("Y-m-d"),
                  'pi'                  => $data[0]->pic,
                  'nilai_awal'          => ($ip->total/$ip->qty),
                  'note'                => $ip->note,
                  'status'              => 1,
                  'create_by_users'     => $this->session->userdata("id"),
                  'create_date'         => date("Y-m-d H:i:s")
              );
              $id_mrp_inventory_department = $this->global_models->insert("mrp_inventory_department", $kirim_inventory);
              
//              sign untuk nilai asset
//              $kirim_nilai_asset = array(
//                  "id_mrp_inventory_department"     => $id_mrp_inventory_department,
//                  "id_mrp_purchase_items"           => $ip->id_mrp_purchase_items,
//                  "title"                           => "Pengadaan Barang",
//                  "tanggal"                         => date("Y-m-d"),
//                  "nilai"                           => ($ip->total/$ip->qty),
//                  'create_by_users'     => $this->session->userdata("id"),
//                  'create_date'         => date("Y-m-d H:i:s")
//              );
//              
//              $id_mrp_inventory_penyusutan = $this->global_models->insert("mrp_inventory_penyusutan", $kirim_nilai_asset);
              
            }
            
          }
          $this->global_models->update("mrp_inventory_purchase", array("id_mrp_inventory_purchase" => $id_mrp_inventory_purchase), array("status" => 4));
//          $this->global_models->insert_batch("mrp_inventory_department", $kirim_inventory);
        }
        else{
        
          $kirim = array(
              "title"               => $pst['title'],
              "id_hrm_department"   => $pst['id_hrm_department'],
              "id_mrp_supplier"     => $pst['id_mrp_supplier'],
              "tanggal"             => $pst['tanggal'],
              "notransaksi"         => $pst['notransaksi'],
              "pic"                 => $pst['pic'],
              "status"              => $pst['status'],
              "note"                => $pst['note'],
              "update_by_users"     => $this->session->userdata("id"),
          );
          $id_mrp_inventory_purchase = $this->global_models->update("mrp_inventory_purchase", array("id_mrp_inventory_purchase" => $pst['id_detail']), 
                  $kirim);
          if($id_mrp_inventory_purchase){
            $this->global_models->update("mrp_inventory_purchase_items", array("id_mrp_inventory_purchase" => $pst['id_detail']), array("status" => 2));
            foreach($pst['id_mrp_inventory'] as $key => $id_mrp_inventory){
              $jumlah = $pst['qty'][$key] * $this->global_models->string_to_number($pst['price'][$key]);
              $discou = $jumlah * $pst['discount'][$key] / 100;
              $kirim_insert = array(
                  "id_mrp_inventory_purchase_items" => $pst['id_mrp_inventory_purchase_items'][$key],
                  "id_mrp_inventory_purchase"     => $pst['id_detail'],
                  "id_mrp_inventory"              => $id_mrp_inventory,
                  "qty"                           => $pst['qty'][$key],
                  "price"                         => $this->global_models->string_to_number($pst['price'][$key]),
                  "discount"                      => $pst['discount'][$key],
                  "total"                         => ($jumlah - $discou),
                  "status"                        => 1,
                  "note"                          => $pst['note_items'][$key],
                  "create_by_users"               => $this->session->userdata("id"),
                  "create_date"                   => date("Y-m-d H:i:s")
              );

              $kirim_update = array(
                  "id_mrp_inventory"              => $id_mrp_inventory,
                  "qty"                           => $pst['qty'][$key],
                  "price"                         => $this->global_models->string_to_number($pst['price'][$key]),
                  "discount"                      => $pst['discount'][$key],
                  "total"                         => ($jumlah - $discou),
                  "status"                        => 1,
                  "note"                          => $pst['note_items'][$key],
                  "update_by_users"               => $this->session->userdata("id"),
              );

              $id_mrp_inventory_purchase_items = $this->global_models->update_duplicate("mrp_inventory_purchase_items", $kirim_insert, $kirim_update);
              
              $id_mrp_inventory_category = $this->global_models->get_field("mrp_inventory", "id_mrp_inventory_category", 
                      array("id_mrp_inventory" => $id_mrp_inventory));
              $debit[] = ($jumlah - $discou);
              $debit_da[] = $this->global_models->get_field("mrp_inventory_category", "id_frm_account", 
                      array("id_mrp_inventory_category" => $id_mrp_inventory_category));

              $total += ($jumlah - $discou);
            }

            if($accept){
              $kirim_hutang = array(
                  "id_mrp_supplier"           => $pst['id_mrp_supplier'],
                  "title"                     => "Order Asset",
                  "notransaksi"               => $pst['notransaksi'],
                  "id_mrp_inventory_purchase" => $pst['id_detail'],
                  "tanggal"                   => $pst['tanggal'],
                  "price"                     => $total,
                  "pos"                       => 2,
                  "note"                      => $pst['title'],
                  "create_by_users"           => $this->session->userdata("id"),
                  "create_date"               => date("Y-m-d H:i:s")
              );
              $id_mrp_hutang_supplier = $this->global_models->insert("mrp_hutang_supplier", $kirim_hutang);

              if($id_mrp_hutang_supplier){
                $id_hutang_asset = $this->nbscache->get_explode("variable", "id_hutang_asset");
//                $id_asset = $this->nbscache->get_explode("variable", "id_asset");
                
                $kirim_payment = array(
                    "id_mrp_inventory_purchase"     => $pst['id_detail'],
                    "id_frm_account"                => $id_hutang_asset[1],
                    "notransaksi"                   => $pst['notransaksi'],
                    "saldo"                         => $total,
                    "pos"                           => 2,
                    "note"                          => "Pengadaan Asset <a href='".site_url("mrp/asset/add-purchase/".$id_mrp_inventory_purchase)."'>".$pst['title']."</a>",
                    "create_by_users"               => $this->session->userdata("id"),
                    "create_date"                   => date("Y-m-d H:i:s")
                );
                
                $id_mrp_inventory_payment_purchase = $this->global_models->insert("mrp_inventory_payment_purchase", $kirim_payment);
                
                $kirim_journal_log = array(
                    "id_frm_journal"      => $this->mfrm->get_journal_current(),
                    "notransaksi"         => $pst['notransaksi'],
                    "saldo"               => $total,
                    "tanggal"             => $pst['tanggal'],
                    "note"                => "Pengadaan Asset <a href='".site_url("mrp/asset/add-purchase/".$pst['id_detail'])."'>{$pst['notransaksi']}</a> -- ".$pst['title'],
                );

                $id_frm_journal_log = $this->mfrm->create_journal_log($kirim_journal_log);
                
                if($id_frm_journal_log){

                    $kredit[] = $total;
                    $kredit_da[] = $id_hutang_asset[1];
                    $this->mfrm->create_journal_log_account($this->mfrm->get_journal_current(), $id_frm_journal_log, $debit, $debit_da, $kredit, $kredit_da);

                } 
              }

            }

            $this->session->set_flashdata('success', 'Data tersimpan');
          }
          else{
            $this->session->set_flashdata('notice', 'Data tidak tersimpan');
          }
        }
      }
      else{
        $kirim = array(
            "title"               => $pst['title'],
            "id_hrm_department"   => $pst['id_hrm_department'],
            "id_mrp_supplier"     => $pst['id_mrp_supplier'],
            "notransaksi"         => $pst['notransaksi'],
            "tanggal"             => $pst['tanggal'],
            "pic"                 => $pst['pic'],
            "status"              => $pst['status'],
            "note"                => $pst['note'],
            "create_by_users"     => $this->session->userdata("id"),
            "create_date"         => date("Y-m-d H:i:s")
        );
        $id_mrp_inventory_purchase = $this->global_models->insert("mrp_inventory_purchase", $kirim);
        if($id_mrp_inventory_purchase){
          foreach($pst['id_mrp_inventory'] as $key => $id_mrp_inventory){
            $jumlah = $pst['qty'][$key] * $this->global_models->string_to_number($pst['price'][$key]);
            $discou = $jumlah * $pst['discount'][$key] / 100;
            
//            if(!$pst['discount'][$key])
//              $pst['discount'][$key] = 0;
            
            $kirim_items[] = array(
                "id_mrp_inventory_purchase"     => $id_mrp_inventory_purchase,
                "id_mrp_inventory"              => $id_mrp_inventory,
                "qty"                           => $pst['qty'][$key],
                "price"                         => $this->global_models->string_to_number($pst['price'][$key]),
                "discount"                      => $pst['discount'][$key],
                "total"                         => ($jumlah - $discou),
                "status"                        => 1,
                "note"                          => $pst['note_items'][$key],
                "create_by_users"               => $this->session->userdata("id"),
                "create_date"                   => date("Y-m-d H:i:s")
            );
          }
          $id_mrp_inventory_purchase_items = $this->global_models->insert_batch("mrp_inventory_purchase_items", $kirim_items);
          $this->session->set_flashdata('success', 'Data tersimpan');
        }
        else{
          $this->session->set_flashdata('notice', 'Data tidak tersimpan');
        }
      }
      redirect("mrp/asset/purchase");
    }
    else{
      $department = $this->global_models->get_dropdown("hrm_department", "id_hrm_department", "title", false);
      $lock = true;
      if($id_mrp_inventory_purchase){
        $items = $this->global_models->get("mrp_inventory_purchase_items", array("id_mrp_inventory_purchase" => $id_mrp_inventory_purchase, "status" => 1));
        $k = 1;
        if($data[0]->status == 4 OR $data[0]->status == 3 OR $data[0]->status == 2){
          $lock = false;
        }
        foreach($items AS $itms){
          $isi[] = array(
            $this->form_eksternal->form_autocomplate("inventory[]", "id_mrp_inventory[]", "inventory_".$k, "id_mrp_inventory_".$k, 
                  site_url("mrp/auto-inventory"), $this->global_models->get_field("mrp_inventory", "title", 
                          array("id_mrp_inventory" => $itms->id_mrp_inventory)), $itms->id_mrp_inventory, "","", "id_mrp_inventory_purchase_items", 
                    $itms->id_mrp_inventory_purchase_items, $lock),
            $this->form_eksternal->form_textarea("note_items[]", $itms->note, "style='height: 30px'", $lock),
            $this->form_eksternal->form_input('qty[]', $itms->qty, "style='width: 30px' onblur='hitung({$k})' id='qty_{$k}'", $lock),
            $this->form_eksternal->form_input_price("price_".$k, 'price[]', $itms->price, "onblur='hitung({$k})' style='width: 90px' id='price_{$k}'", $lock),
            $this->form_eksternal->form_input('discount[]', $itms->discount,"onblur='hitung({$k})' style='width: 30px' id='discount_{$k}'", $lock)." %",
            "<div id='total_{$k}' style='width:100%; text-align: right'>Rp ".number_format($itms->total,0,",", ".")."</div>",
          );
          $tr[] = "tr_".$k;
          $k++;
        }
      }
      else{
        $isi[1] = array(
          $this->form_eksternal->form_autocomplate("inventory[]", "id_mrp_inventory[]", "inventory_1", "id_mrp_inventory_1", 
                site_url("mrp/auto-inventory"), ""),
          $this->form_eksternal->form_textarea("note_items[]", "", "style='height: 30px'"),
          $this->form_eksternal->form_input('qty[]', "", "style='width: 30px' onblur='hitung(1)' id='qty_1'"),
          $this->form_eksternal->form_input_price("price_1", 'price[]', "", "onblur='hitung(1)' style='width: 90px' id='price_1'"),
          $this->form_eksternal->form_input('discount[]', "","onblur='hitung(1)' style='width: 30px' id='discount_1'")." %",
          "<div id='total_1' style='width:100%; text-align: right'></div>",
        );
        $tr[1] = "tr_1";
      }
      
      $supplier = $this->global_models->get_dropdown("mrp_supplier", "id_mrp_supplier", "title");
      
//      $this->debug($lock, true);
      $this->template->build("asset/add-asset-purchase",
        array(
              'url'         => base_url()."themes/".DEFAULTTHEMES."/",
              'menu'        => 'mrp/asset/purchase',
              'title'       => lang("asset_purchase"),
              'detail'      => $data,
              'department'  => $department,
              'isi'         => $isi,
              'tr'          => $tr,
              'supplier'    => $supplier,
              'lock'        => $lock
            ));
      $this->template
        ->set_layout('default')
        ->build("asset/add-asset-purchase");
    }
  }
  
	public function inventory($id_hrm_department){
    $department = $this->global_models->get("hrm_department", array("id_hrm_department" => $id_hrm_department));
    $inventory = $this->global_models->get_query("
      SELECT A.*, B.title, count(A.id_mrp_inventory) AS qty
      FROM mrp_inventory_department AS A
      LEFT JOIN mrp_inventory AS B ON A.id_mrp_inventory = B.id_mrp_inventory
      WHERE A.id_hrm_department = $id_hrm_department AND A.status = 1
      GROUP BY A.id_mrp_inventory
      ");
    $this->template->build("asset/inventory-department",
      array(
            'url'         => base_url()."themes/".DEFAULTTHEMES."/",
            'menu'        => 'mrp/asset/department',
            'title'       => lang("inventory")." ".$department[0]->title,
            'department'  => $department,
            'data'        => $inventory
          ));
    $this->template
      ->set_layout('default')
      ->build("asset/inventory-department");
  }
  
	public function history_inventory($id_hrm_department, $id_mrp_inventory, $id_mrp_inventory_department = 0){
    $mrp_inventory = $this->global_models->get_dropdown("mrp_inventory_department", "id_mrp_inventory_department", "sn", false, array("id_mrp_inventory" => $id_mrp_inventory, 'status =' => 1, "id_hrm_department" => $id_hrm_department));
    if($id_mrp_inventory_department == 0){
      foreach($mrp_inventory as $kmi => $mi){
        $inventory = $this->global_models->get_query("
          SELECT A.*, C.name AS brand, B.picture AS picture, B.title AS inventory
          FROM mrp_inventory_department AS A
          LEFT JOIN mrp_inventory AS B ON A.id_mrp_inventory = B.id_mrp_inventory
          LEFT JOIN mrp_inventory_brand AS C ON B.id_mrp_inventory_brand = C.id_mrp_inventory_brand
          WHERE A.id_mrp_inventory_department = {$kmi}
          ");
        break;
      }
    }
    else{
      $inventory = $this->global_models->get_query("
          SELECT A.*, C.name AS brand, B.picture AS picture, B.title AS inventory
          FROM mrp_inventory_department AS A
          LEFT JOIN mrp_inventory AS B ON A.id_mrp_inventory = B.id_mrp_inventory
          LEFT JOIN mrp_inventory_brand AS C ON B.id_mrp_inventory_brand = C.id_mrp_inventory_brand
          WHERE A.id_mrp_inventory_department = {$id_mrp_inventory_department}
          ");
    }
//    $this->debug($mrp_inventory, true);
    
    $history = $this->global_models->get("mrp_history_inventory", array("id_mrp_inventory_department" => $inventory[0]->id_mrp_inventory_department));
    
    $penyusutan = $this->global_models->get("mrp_inventory_penyusutan", array("id_mrp_inventory_department" => $inventory[0]->id_mrp_inventory_department));
    
    $this->template->build("asset/history-inventory",
      array(
            'url'                         => base_url()."themes/".DEFAULTTHEMES."/",
            'menu'                        => 'mrp/asset/department',
            'inventory'                   => $inventory,
            'mrp_inventory'               => $mrp_inventory,
            'id_mrp_inventory_department' => $id_mrp_inventory_department,
            'history'                     => $history,
            'penyusutan'                  => $penyusutan
          ));
    $this->template
      ->set_layout('default')
      ->build("asset/history-inventory");
  }
  
	public function department(){
    $department = $this->global_models->get("hrm_department");
    $this->template->build("asset/department",
      array(
            'url'         => base_url()."themes/".DEFAULTTHEMES."/",
            'menu'        => 'mrp/asset/department',
            'title'       => lang("department"),
            'data'        => $department
          ));
    $this->template
      ->set_layout('default')
      ->build("asset/department");
	}
  
  function schedule($id_mrp_inventory_department, $year = ""){
    if(!$year){
      $this->session->set_userdata(
                              array("mrp_block_hari" => "",
                                    "mrp_start_block" => ""
                                      ));
      $year = date("Y");
    }
    $this->template->build("asset/schedule",
      array(
            'url'         => base_url()."themes/".DEFAULTTHEMES."/",
            'menu'        => 'mrp/asset/department',
            'title'       => lang("mrp_schedule_asset"),
            'cur_year'    => $year,
            'id_mrp_inventory_department' => $id_mrp_inventory_department,
          ));
    $this->template
      ->set_layout('default')
      ->build("asset/schedule");
  }
	
  public function booking(){
    if($this->input->post()){
      if($this->input->post('cari') == 's'){
        $session_cari = array(
            "mrp_asset_booking_search_title"        => $this->input->post("s_title"),
            "mrp_asset_booking_search_pic"        => $this->input->post("s_pic"),
            "mrp_asset_booking_search_date1"        => $this->input->post("s_date1"),
            "mrp_asset_booking_search_date2"        => $this->input->post("s_date2"),
            "mrp_asset_booking_search_status"     => $this->input->post("s_status"),
            "mrp_asset_booking_search_department"     => $this->input->post("s_department"),
        );
        if(!$session_cari['mrp_asset_booking_search_date2'])
          $session_cari['mrp_asset_booking_search_date2'] = $session_cari['mrp_asset_booking_search_date1'];
        
        $this->session->set_userdata($session_cari);
      }
      else{
        $session_cari = array(
            "mrp_asset_booking_search_title"        => "",
            "mrp_asset_booking_search_pic"        => "",
            "mrp_asset_booking_search_date1"            => "",
            "mrp_asset_booking_search_date2"            => "",
            "mrp_asset_booking_search_status"     => "",
            "mrp_asset_booking_search_department"     => "",
        );
        $this->session->unset_userdata($session_cari);
      }
      redirect("mrp/asset/booking");
    }
    
    $where = "WHERE 1 = 1 ";
    if($this->session->userdata("mrp_asset_booking_search_title"))
      $where .= "AND LOWER(A.title) LIKE '%".strtolower($this->session->userdata("mrp_asset_booking_search_title"))."%' ";
    
    if($this->session->userdata("mrp_asset_booking_search_pic"))
      $where .= "AND LOWER(A.pic) LIKE '%".strtolower($this->session->userdata("mrp_asset_booking_search_pic"))."%' ";
    
    if($this->session->userdata("mrp_asset_booking_search_status"))
      $where .= "AND A.status = ".$this->session->userdata("mrp_asset_booking_search_status")." ";
    
    if($this->session->userdata("mrp_asset_booking_search_department"))
      $where .= "AND A.id_hrm_department = ".$this->session->userdata("mrp_asset_booking_search_department")." ";
    
    if($this->session->userdata("mrp_asset_booking_search_date1")){
      $where .= "
        AND ((A.tanggalin BETWEEN '{$this->session->userdata("mrp_asset_booking_search_date1")}' AND '{$this->session->userdata("mrp_asset_booking_search_date2")}') OR (A.tanggalout BETWEEN '{$this->session->userdata("mrp_asset_booking_search_date1")}' AND '{$this->session->userdata("mrp_asset_booking_search_date2")}')) 
        ";
    }
//    $this->debug($where, true);
    $total = $this->global_models->get_query("
      SELECT count(A.id_mrp_inventory_booking) AS jumlah
      FROM mrp_inventory_booking AS A
      {$where}
      ");
      
    $this->template->build("asset/booking",
      array(
            'url'         => base_url()."themes/".DEFAULTTHEMES."/",
            'menu'        => 'mrp/asset/booking',
            'title'       => lang("asset_booking"),
            'total'       => $total[0]->jumlah,
            'sdepartment' => $this->global_models->get_dropdown("hrm_department", "id_hrm_department", "title"),
          ));
    $this->template
      ->set_layout('default')
      ->build("asset/booking");
	}
  
  public function purchase(){
    if($this->input->post()){
      if($this->input->post('cari') == 's'){
        $session_cari = array(
            "crm_quotation_search_title"        => $this->input->post("s_title"),
            "crm_quotation_search_up_to"        => $this->input->post("s_up_to"),
            "crm_quotation_search_date1"        => $this->input->post("s_date1"),
            "crm_quotation_search_date2"        => $this->input->post("s_date2"),
            "crm_quotation_search_telphone"     => $this->input->post("s_telphone"),
        );
        if(!$session_cari['crm_quotation_search_date2'])
          $session_cari['crm_quotation_search_date2'] = $session_cari['crm_quotation_search_date1'];
        
        $this->session->set_userdata($session_cari);
      }
      else{
        $session_cari = array(
            "crm_quotation_search_title"        => "",
            "crm_quotation_search_up_to"        => "",
            "crm_quotation_search_date1"            => "",
            "crm_quotation_search_date2"            => "",
            "crm_quotation_search_telphone"     => "",
        );
        $this->session->unset_userdata($session_cari);
      }
      redirect("crm/quotation");
    }
    
    $where = "WHERE 1 = 1 ";
    if($this->session->userdata("crm_quotation_search_title"))
      $where .= "AND LOWER(B.title) LIKE '%".strtolower($this->session->userdata("crm_quotation_search_title"))."%' ";
    
    if($this->session->userdata("crm_quotation_search_up_to"))
      $where .= "AND LOWER(A.up_to) LIKE '%".strtolower($this->session->userdata("crm_quotation_search_up_to"))."%' ";
    
    if($this->session->userdata("crm_quotation_search_telphone"))
      $where .= "AND LOWER(A.telphone) LIKE '%".strtolower($this->session->userdata("crm_quotation_search_telphone"))."%' ";
    
    if($this->session->userdata("crm_quotation_search_date1")){
      $where .= "
        AND (A.create_date BETWEEN '{$this->session->userdata("crm_quotation_search_date1")}' AND '{$this->session->userdata("crm_quotation_search_date2")}') 
        ";
    }
    
    $total = $this->global_models->get_query("
      SELECT count(A.id_mrp_inventory_purchase) AS jumlah
      FROM mrp_inventory_purchase AS A
      {$where}
      ");
      
    $this->template->build("asset/purchase",
      array(
            'url'         => base_url()."themes/".DEFAULTTHEMES."/",
            'menu'        => 'mrp/asset/purchase',
            'title'       => lang("asset_purchase"),
            'total'       => $total[0]->jumlah
          ));
    $this->template
      ->set_layout('default')
      ->build("asset/purchase");
	}
  
  function get_inventory_in_department($id_hrm_department){
    $inventory = $this->global_models->get_query("
      SELECT A.*, B.title AS inventory
      FROM mrp_inventory_department AS A
      LEFT JOIN mrp_inventory AS B ON A.id_mrp_inventory = B.id_mrp_inventory
      WHERE A.id_hrm_department	= $id_hrm_department
    ");
    foreach ($inventory AS $inv){
      $inventory_dropdown[$inv->id_mrp_inventory_department] = $inv->inventory."-".$inv->sn;
    }
    print json_encode($inventory_dropdown);
    die;
  }
  
  public function ajax_booking($field, $sort, $total = 0, $start = 0){
    
    $where = "WHERE 1 = 1 ";
    if($this->session->userdata("mrp_asset_booking_search_title"))
      $where .= "AND LOWER(A.title) LIKE '%".strtolower($this->session->userdata("mrp_asset_booking_search_title"))."%' ";
    
    if($this->session->userdata("mrp_asset_booking_search_pic"))
      $where .= "AND LOWER(A.pic) LIKE '%".strtolower($this->session->userdata("mrp_asset_booking_search_pic"))."%' ";
    
    if($this->session->userdata("mrp_asset_booking_search_status"))
      $where .= "AND A.status = ".$this->session->userdata("mrp_asset_booking_search_status")." ";
    
    if($this->session->userdata("mrp_asset_booking_search_department"))
      $where .= "AND A.id_hrm_department = ".$this->session->userdata("mrp_asset_booking_search_department")." ";
    
    if($this->session->userdata("mrp_asset_booking_search_date1")){
      $where .= "
        AND ((A.tanggalin BETWEEN '{$this->session->userdata("mrp_asset_booking_search_date1")}' AND '{$this->session->userdata("mrp_asset_booking_search_date2")}') OR (A.tanggalout BETWEEN '{$this->session->userdata("mrp_asset_booking_search_date1")}' AND '{$this->session->userdata("mrp_asset_booking_search_date2")}')) 
        ";
    }
    
    $data = $this->global_models->get_query("
      SELECT A.*, B.sn AS sn, C.title AS inventory, D.title AS department
      FROM mrp_inventory_booking AS A
      LEFT JOIN mrp_inventory_department AS B ON A.id_mrp_inventory_department = B.id_mrp_inventory_department
      LEFT JOIN mrp_inventory AS C ON B.id_mrp_inventory = C.id_mrp_inventory
      LEFT JOIN hrm_department AS D ON A.id_hrm_department = D.id_hrm_department
      {$where}
      ORDER BY {$field} {$sort} LIMIT {$start},10
      ");
      
    $status_booking = array(
        1   => "<span class='label label-info'>Submitted</span>",
        2   => "<span class='label label-success'>Accepted</span>",
        3   => "<span class='label label-important'>Rejected</span>"
    );
    
    foreach ($data as $key => $value) {
      $payment = "";
      if($value->status == 2 AND $value->price > 0){
        $payment = "<li><a href='".site_url("mrp/asset/payment-booking/".$value->id_mrp_inventory_booking)."'>Payment</a></li>";
      }
      print "
      <tr class='ajax-quotation'>
        <td>{$value->title}</td>
        <td>{$value->inventory} {$value->sn}</td>
        <td>{$value->department}</td>
        <td>".date("Y-m-d H:i:s", strtotime($value->tanggalin))."</td>
        <td>".date("Y-m-d H:i:s", strtotime($value->tanggalout))."</td>
        <td>{$value->pic}</td>
        <td>{$status_booking[$value->status]}</td>
        <td>
          <div class='btn-group'>
            <button data-toggle='dropdown' class='btn btn-small dropdown-toggle'>Action<span class='caret'></span></button>
            <ul class='dropdown-menu'>
              <li><a href='".site_url("mrp/asset/add-booking/".$value->id_mrp_inventory_booking)."'>Edit</a></li>
              $payment
            </ul>
          </div>
        </td>
      </tr>";
        
    }
    
    $this->load->library('pagination');

    $config['base_url'] = '';
    $config['total_rows'] = $total;
    $config['per_page'] = 10; 
    $config['uri_segment'] = 7; 
    $config['cur_tag_open'] = "<li class='active'><a href='javascript:void(0)'>"; 
    $config['cur_tag_close'] = "</a></li>"; 
    $config['first_tag_open'] = "<li>"; 
    $config['first_tag_close'] = "</li>"; 
    $config['last_tag_open'] = "<li>"; 
    $config['last_tag_close'] = "</li>"; 
    $config['next_tag_open'] = "<li>"; 
    $config['next_tag_close'] = "</li>"; 
    $config['prev_tag_open'] = "<li>"; 
    $config['prev_tag_close'] = "</li>"; 
    $config['num_tag_open'] = "<li>"; 
    $config['num_tag_close'] = "</li>";
    $config['function_js'] = "load_quotation";

    $this->pagination->initialize($config); 
    print "
    <tr class='ajax-quotation'>
      <td colspan='8'>
        <div class='pagination'>
          <ul>
          ".$this->pagination->create_links_ajax()."
          </ul>
        </div>
      </td>
    </tr>";
    die;
  }
  
  public function ajax_purchase($field, $sort, $total = 0, $start = 0){
    
    $where = "WHERE 1 = 1 ";
    if($this->session->userdata("mrp_asset_booking_search_title"))
      $where .= "AND LOWER(A.title) LIKE '%".strtolower($this->session->userdata("mrp_asset_booking_search_title"))."%' ";
    
    if($this->session->userdata("mrp_asset_booking_search_pic"))
      $where .= "AND LOWER(A.pic) LIKE '%".strtolower($this->session->userdata("mrp_asset_booking_search_pic"))."%' ";
    
    if($this->session->userdata("mrp_asset_booking_search_status"))
      $where .= "AND A.status = ".$this->session->userdata("mrp_asset_booking_search_status")." ";
    
    if($this->session->userdata("mrp_asset_booking_search_department"))
      $where .= "AND A.id_hrm_department = ".$this->session->userdata("mrp_asset_booking_search_department")." ";
    
    if($this->session->userdata("mrp_asset_booking_search_date1")){
      $where .= "
        AND ((A.tanggalin BETWEEN '{$this->session->userdata("mrp_asset_booking_search_date1")}' AND '{$this->session->userdata("mrp_asset_booking_search_date2")}') OR (A.tanggalout BETWEEN '{$this->session->userdata("mrp_asset_booking_search_date1")}' AND '{$this->session->userdata("mrp_asset_booking_search_date2")}')) 
        ";
    }
    
    $data = $this->global_models->get_query("
      SELECT A.*, B.title AS department
      FROM mrp_inventory_purchase AS A
      LEFT JOIN hrm_department AS B ON A.id_hrm_department = B.id_hrm_department
      {$where}
      ORDER BY {$field} {$sort} LIMIT {$start},10
      ");
      
    $status_booking = array(
        1   => "<span class='label label-info'>Submitted</span>",
        2   => "<span class='label label-success'>Accepted</span>",
        3   => "<span class='label label-important'>Rejected</span>",
        4   => "<span class='label label-success'>Received</span>"
    );
    
    foreach ($data as $key => $value) {
      $cicilan = "";
      if($value->status == 2 OR $value->status == 4){
        $cicilan = "<li><a href='".site_url("mrp/asset/payment-purchase-asset/".$value->id_mrp_inventory_purchase)."'>Payment</a></li>";
      }
      
      print "
      <tr class='ajax-quotation'>
        <td>{$value->title}</td>
        <td>{$value->department}</td>
        <td>".date("Y-m-d", strtotime($value->tanggal))."</td>
        <td>{$value->pic}</td>
        <td>{$status_booking[$value->status]}</td>
        <td>
          <div class='btn-group'>
            <button data-toggle='dropdown' class='btn btn-small dropdown-toggle'>Action<span class='caret'></span></button>
            <ul class='dropdown-menu'>
              <li><a href='".site_url("mrp/asset/add-purchase/".$value->id_mrp_inventory_purchase)."'>Edit</a></li>
              $cicilan
            </ul>
          </div>
        </td>
      </tr>";
        
    }
    
    $this->load->library('pagination');

    $config['base_url'] = '';
    $config['total_rows'] = $total;
    $config['per_page'] = 10; 
    $config['uri_segment'] = 7; 
    $config['cur_tag_open'] = "<li class='active'><a href='javascript:void(0)'>"; 
    $config['cur_tag_close'] = "</a></li>"; 
    $config['first_tag_open'] = "<li>"; 
    $config['first_tag_close'] = "</li>"; 
    $config['last_tag_open'] = "<li>"; 
    $config['last_tag_close'] = "</li>"; 
    $config['next_tag_open'] = "<li>"; 
    $config['next_tag_close'] = "</li>"; 
    $config['prev_tag_open'] = "<li>"; 
    $config['prev_tag_close'] = "</li>"; 
    $config['num_tag_open'] = "<li>"; 
    $config['num_tag_close'] = "</li>";
    $config['function_js'] = "load_quotation";

    $this->pagination->initialize($config); 
    print "
    <tr class='ajax-quotation'>
      <td colspan='8'>
        <div class='pagination'>
          <ul>
          ".$this->pagination->create_links_ajax()."
          </ul>
        </div>
      </td>
    </tr>";
    die;
  }
  
  function add_items_for_purchase(){
    $key = $this->input->post('no');
    $isi = array(
      $this->form_eksternal->form_autocomplate("inventory[]", "id_mrp_inventory[]", "inventory_".$key, "id_mrp_inventory_".$key, 
              site_url("mrp/auto-inventory"), ""),
      $this->form_eksternal->form_textarea("note_items[]", "", "style='height: 30px'"),
      $this->form_eksternal->form_input('qty[]', "", "style='width: 30px'"),
      $this->form_eksternal->form_input_price("price_{$key}", 'price[]', "", "style='width: 90px'"),
      $this->form_eksternal->form_input('discount[]', "","style='width: 30px'")." %",
      "<div id='total_{$key}' style='width:100%; text-align: right'></div>",
    );
    foreach($isi as $si){
      $sisip .= "<td>{$si}</td>";
    }
    print <<<EOD
    <tr id='tr_{$key}'>{$sisip}
      <td><a href='javascript:void(0)' class='remove-element' onclick='del_row_lokal("tr_{$key}")' title='Remove' >Remove</a></td>
    </tr>
EOD;
    die;
  }
  
  public function payment_purchase_asset($id_mrp_inventory_purchase){
    
    $total = $this->global_models->get_query("
      SELECT count(A.id_mrp_inventory_payment_purchase) AS jumlah
      FROM mrp_inventory_payment_purchase AS A WHERE A.id_mrp_inventory_purchase = '{$id_mrp_inventory_purchase}'
      ");
    $this->template->build("asset/payment-purchase-asset",
      array(
            'url'         => base_url()."themes/".DEFAULTTHEMES."/",
            'menu'        => 'mrp/asset/purchase',
            'title'       => lang("mrp_payment_purchase")." ".$this->global_models->get_field("mrp_inventory_purchase", "title", array("id_mrp_inventory_purchase" => $id_mrp_inventory_purchase)),
            'total'       => $total[0]->jumlah,
            'id_mrp_inventory_purchase'         => $id_mrp_inventory_purchase
          ));
    $this->template
      ->set_layout('default')
      ->build("asset/payment-purchase-asset");
	}
  
  public function payment_booking($id_mrp_inventory_booking){
    
    $total = $this->global_models->get_query("
      SELECT count(A.id_mrp_inventory_payment_booking) AS jumlah
      FROM mrp_inventory_payment_booking AS A WHERE A.id_mrp_inventory_booking = '{$id_mrp_inventory_booking}'
      ");
    $this->template->build("asset/payment-booking",
      array(
            'url'         => base_url()."themes/".DEFAULTTHEMES."/",
            'menu'        => 'mrp/asset/booking',
            'title'       => lang("mrp_payment_booking")." ".$this->global_models->get_field("mrp_inventory_booking", "title", array("id_mrp_inventory_booking" => $id_mrp_inventory_booking)),
            'total'       => $total[0]->jumlah,
            'id_mrp_inventory_booking'         => $id_mrp_inventory_booking
          ));
    $this->template
      ->set_layout('default')
      ->build("asset/payment-booking");
	}
  
  public function ajax_payment_purchase_asset($id_mrp_inventory_purchase, $total = 0, $start = 0){
    
    $data = $this->global_models->get_query("
      SELECT A.*
      FROM mrp_inventory_payment_purchase AS A
      WHERE A.id_mrp_inventory_purchase = '{$id_mrp_inventory_purchase}'
      ORDER BY A.create_date DESC LIMIT {$start},10
      ");
    $total_debit = $this->global_models->get_query("
      SELECT SUM(A.saldo) AS saldo
      FROM mrp_inventory_payment_purchase AS A
      WHERE A.id_mrp_inventory_purchase = '{$id_mrp_inventory_purchase}' AND A.pos = 1 AND A.create_date <= '{$data[0]->create_date}'
      ");
      
    $total_kredit = $this->global_models->get_query("
      SELECT SUM(A.saldo) AS saldo
      FROM mrp_inventory_payment_purchase AS A
      WHERE A.id_mrp_inventory_purchase = '{$id_mrp_inventory_purchase}' AND A.pos = 2 AND A.create_date <= '{$data[0]->create_date}'
      ");
//    $this->debug($total_debit);
//    $this->debug($total_kredit, true);
//    $total_kredit = $this->global_models->get_field("frm_journal_log_account", "SUM(saldo)", 
//            array("id_frm_account" => $id_frm_account, "id_frm_journal" => $id_frm_journal, "pos" => 2, "tanggal >" => $data[0]->tanggal));
    
    $pos_asli = $this->global_models->get_field("frm_account", "pos", array("id_frm_account" => $id_frm_account));
    if($pos_asli == 1)
      $total_akhir = $total_debit[0]->saldo - $total_kredit[0]->saldo;
    else
      $total_akhir = $total_kredit[0]->saldo - $total_debit[0]->saldo;
    
    foreach ($data as $key => $value) {
      if($value->pos == 1){
        $saldo_debit = $value->saldo;
        $saldo_kredit = "";
        
      }
      else{
        $saldo_debit = "";
        $saldo_kredit = $value->saldo;
        
      }
      if($value->id_keuangan_mahasiswa_jenis_biaya){
        $title = "Tanggungan ".$value->jenis_biaya. " ". $value->id_semester." - ".$value->tahun;
      }
      else{
        $title = $value->note;
      }
      print "
      <tr class='ajax-quotation'>
        <td>{$value->create_date}</td>
        <td>{$title}</td>
        <td>{$value->notransaksi}</td>
        <td style='text-align: right'>Rp ".  number_format($saldo_debit, 0, ",", ".")."</td>
        <td style='text-align: right'>Rp ".  number_format($saldo_kredit, 0, ",", ".")."</td>
        <td style='text-align: right; font-weight: bold;'>Rp ".  number_format($total_akhir, 0, ",", ".")."</td>
      </tr>";
      
      if($value->pos == 1){
        $total_akhir = $total_akhir + $saldo_debit;
      }
      else{
        $total_akhir = $total_akhir - $saldo_kredit;
      }
    }
    
    $this->load->library('pagination');

    $config['base_url'] = '';
    $config['total_rows'] = $total;
    $config['per_page'] = 10; 
    $config['uri_segment'] = 6; 
    $config['cur_tag_open'] = "<li class='active'><a href='javascript:void(0)'>"; 
    $config['cur_tag_close'] = "</a></li>"; 
    $config['first_tag_open'] = "<li>"; 
    $config['first_tag_close'] = "</li>"; 
    $config['last_tag_open'] = "<li>"; 
    $config['last_tag_close'] = "</li>"; 
    $config['next_tag_open'] = "<li>"; 
    $config['next_tag_close'] = "</li>"; 
    $config['prev_tag_open'] = "<li>"; 
    $config['prev_tag_close'] = "</li>"; 
    $config['num_tag_open'] = "<li>"; 
    $config['num_tag_close'] = "</li>";
    $config['function_js'] = "load_quotation";

    $this->pagination->initialize($config); 
    print "
    <tr class='ajax-quotation'>
      <td colspan='6'>
        <div class='pagination'>
          <ul>
          ".$this->pagination->create_links_ajax()."
          </ul>
        </div>
      </td>
    </tr>";
    die;
  }
  
  public function ajax_payment_booking($id_mrp_inventory_booking, $total = 0, $start = 0){
    
    $data = $this->global_models->get_query("
      SELECT A.*
      FROM mrp_inventory_payment_booking AS A
      WHERE A.id_mrp_inventory_booking = '{$id_mrp_inventory_booking}'
      ORDER BY A.create_date DESC LIMIT {$start},10
      ");
    $total_debit = $this->global_models->get_query("
      SELECT SUM(A.saldo) AS saldo
      FROM mrp_inventory_payment_booking AS A
      WHERE A.id_mrp_inventory_booking = '{$id_mrp_inventory_booking}' AND A.pos = 1 AND A.create_date <= '{$data[0]->create_date}'
      ");
      
    $total_kredit = $this->global_models->get_query("
      SELECT SUM(A.saldo) AS saldo
      FROM mrp_inventory_payment_booking AS A
      WHERE A.id_mrp_inventory_booking = '{$id_mrp_inventory_booking}' AND A.pos = 2 AND A.create_date <= '{$data[0]->create_date}'
      ");
//    $this->debug($total_debit);
//    $this->debug($total_kredit, true);
//    $total_kredit = $this->global_models->get_field("frm_journal_log_account", "SUM(saldo)", 
//            array("id_frm_account" => $id_frm_account, "id_frm_journal" => $id_frm_journal, "pos" => 2, "tanggal >" => $data[0]->tanggal));
    
    $pos_asli = $this->global_models->get_field("frm_account", "pos", array("id_frm_account" => $id_frm_account));
    if($pos_asli == 1)
      $total_akhir = $total_debit[0]->saldo - $total_kredit[0]->saldo;
    else
      $total_akhir = $total_kredit[0]->saldo - $total_debit[0]->saldo;
    
    foreach ($data as $key => $value) {
      if($value->pos == 1){
        $saldo_debit = $value->saldo;
        $saldo_kredit = "";
        
      }
      else{
        $saldo_debit = "";
        $saldo_kredit = $value->saldo;
        
      }
      if($value->id_keuangan_mahasiswa_jenis_biaya){
        $title = "Tanggungan ".$value->jenis_biaya. " ". $value->id_semester." - ".$value->tahun;
      }
      else{
        $title = $value->note;
      }
      print "
      <tr class='ajax-quotation'>
        <td>{$value->create_date}</td>
        <td>{$title}</td>
        <td>{$value->notransaksi}</td>
        <td style='text-align: right'>Rp ".  number_format($saldo_debit, 0, ",", ".")."</td>
        <td style='text-align: right'>Rp ".  number_format($saldo_kredit, 0, ",", ".")."</td>
        <td style='text-align: right; font-weight: bold;'>Rp ".  number_format($total_akhir, 0, ",", ".")."</td>
      </tr>";
      
      if($value->pos == 1){
        $total_akhir = $total_akhir + $saldo_debit;
      }
      else{
        $total_akhir = $total_akhir - $saldo_kredit;
      }
    }
    
    $this->load->library('pagination');

    $config['base_url'] = '';
    $config['total_rows'] = $total;
    $config['per_page'] = 10; 
    $config['uri_segment'] = 6; 
    $config['cur_tag_open'] = "<li class='active'><a href='javascript:void(0)'>"; 
    $config['cur_tag_close'] = "</a></li>"; 
    $config['first_tag_open'] = "<li>"; 
    $config['first_tag_close'] = "</li>"; 
    $config['last_tag_open'] = "<li>"; 
    $config['last_tag_close'] = "</li>"; 
    $config['next_tag_open'] = "<li>"; 
    $config['next_tag_close'] = "</li>"; 
    $config['prev_tag_open'] = "<li>"; 
    $config['prev_tag_close'] = "</li>"; 
    $config['num_tag_open'] = "<li>"; 
    $config['num_tag_close'] = "</li>";
    $config['function_js'] = "load_quotation";

    $this->pagination->initialize($config); 
    print "
    <tr class='ajax-quotation'>
      <td colspan='6'>
        <div class='pagination'>
          <ul>
          ".$this->pagination->create_links_ajax()."
          </ul>
        </div>
      </td>
    </tr>";
    die;
  }
  
  public function pay_purchase($id_mrp_inventory_purchase, $id_mrp_inventory_payment_purchase = 0){
    if($this->input->post(NULL)){
      $pst = $this->input->post(NULL);
      if($pst['id_detail']){
        $kirim = array(
            "title"               => $pst['title'],
            "code"                => $pst['code'],
            "sort"                => $pst['sort'],
            "update_by_users"     => $this->session->userdata("id")
        );
        $id_keuangan_mahasiswa_jenis_biaya = $this->global_models->update("keuangan_mahasiswa_jenis_biaya", array("id_keuangan_mahasiswa_jenis_biaya" => $pst['id_detail']),$kirim);
      }
      else{
        $id_bayar_hutang_asset = $this->nbscache->get_explode("variable", "id_bayar_hutang_asset");
        $id_hutang_asset = $this->nbscache->get_explode("variable", "id_hutang_asset");
          
        $kirim = array(
            "id_mrp_inventory_purchase"     => $pst['id_mrp_inventory_purchase'],
            "id_frm_account"                => $id_hutang_asset[1],
            "notransaksi"                   => $pst['notransaksi'],
            "saldo"                         => $this->global_models->string_to_number($pst['saldo']),
            "pos"                           => 1,
            "note"                          => $pst['note'],
            "create_by_users"               => $this->session->userdata("id"),
            "create_date"                   => $pst['tanggal']
        );
        $id_mrp_inventory_payment_purchase = $this->global_models->insert("mrp_inventory_payment_purchase", $kirim);
        
        $kirim_journal_log = array(
            "id_frm_journal"      => $this->mfrm->get_journal_current(),
            "notransaksi"         => $pst['notransaksi'],
            "saldo"               => $this->global_models->string_to_number($pst['saldo']),
            "tanggal"             => $pst['tanggal'],
            "note"                => "Pembayaran Hutang <a href='".site_url("mrp/asset/payment-purchase-asset/".$pst['id_mrp_inventory_purchase'])."'>{$pst['notransaksi']}</a> -- ",
        );

        $id_frm_journal_log = $this->mfrm->create_journal_log($kirim_journal_log);

        if($id_frm_journal_log){

            $debit[] = $this->global_models->string_to_number($pst['saldo']);
            $debit_da[] = $id_hutang_asset[1];

            $kredit[] = $this->global_models->string_to_number($pst['saldo']);
            $kredit_da[] = $id_bayar_hutang_asset[1];
            $this->mfrm->create_journal_log_account($this->mfrm->get_journal_current(), $id_frm_journal_log, $debit, $debit_da, $kredit, $kredit_da);

        }
        
      }
      if($id_mrp_inventory_payment_purchase){
        $this->session->set_flashdata('success', 'Data tersimpan');
      }
      else{
        $this->session->set_flashdata('notice', 'Data tidak tersimpan');
      }
      redirect("mrp/asset/payment-purchase-asset/".$pst['id_mrp_inventory_purchase']);
    }
    else{
      $this->template->build("asset/add-pay-purchase",
        array(
              'url'         => base_url()."themes/".DEFAULTTHEMES."/",
              'menu'        => 'mrp/asset/purchase',
            'title'       => lang("mrp_payment_purchase")." ".$this->global_models->get_field("mrp_inventory_purchase", "title", array("id_mrp_inventory_purchase" => $id_mrp_inventory_purchase)),
              'detail'      => $detail,
              'id_mrp_inventory_purchase'         => $id_mrp_inventory_purchase
            ));
      $this->template
        ->set_layout('default')
        ->build("asset/add-pay-purchase");
    }
	}
  
  public function pay_booking($id_mrp_inventory_booking, $id_mrp_inventory_payment_booking = 0){
    if($this->input->post(NULL)){
      $pst = $this->input->post(NULL);
      if($pst['id_detail']){
        $kirim = array(
            "title"               => $pst['title'],
            "code"                => $pst['code'],
            "sort"                => $pst['sort'],
            "update_by_users"     => $this->session->userdata("id")
        );
        $id_keuangan_mahasiswa_jenis_biaya = $this->global_models->update("keuangan_mahasiswa_jenis_biaya", array("id_keuangan_mahasiswa_jenis_biaya" => $pst['id_detail']),$kirim);
      }
      else{
        $id_bayar_piutang_asset = $this->nbscache->get_explode("variable", "id_bayar_piutang_asset");
        $id_piutang_pendapataan_asset = $this->nbscache->get_explode("variable", "id_piutang_pendapataan_asset");
          
        $kirim = array(
            "id_mrp_inventory_booking"      => $pst['id_mrp_inventory_booking'],
            "id_frm_account"                => $id_piutang_pendapataan_asset[1],
            "notransaksi"                   => $pst['notransaksi'],
            "saldo"                         => $this->global_models->string_to_number($pst['saldo']),
            "pos"                           => 1,
            "note"                          => $pst['note'],
            "create_by_users"               => $this->session->userdata("id"),
            "create_date"                   => $pst['tanggal']
        );
        $id_mrp_inventory_payment_booking = $this->global_models->insert("mrp_inventory_payment_booking", $kirim);
        
        $kirim_journal_log = array(
            "id_frm_journal"      => $this->mfrm->get_journal_current(),
            "notransaksi"         => $pst['notransaksi'],
            "saldo"               => $this->global_models->string_to_number($pst['saldo']),
            "tanggal"             => $pst['tanggal'],
            "note"                => "Pembayaran Piutang <a href='".site_url("mrp/asset/payment-booking/".$pst['id_mrp_inventory_booking'])."'>{$pst['notransaksi']}</a>",
        );

        $id_frm_journal_log = $this->mfrm->create_journal_log($kirim_journal_log);

        if($id_frm_journal_log){

            $debit[] = $this->global_models->string_to_number($pst['saldo']);
            $debit_da[] = $id_bayar_piutang_asset[1];

            $kredit[] = $this->global_models->string_to_number($pst['saldo']);
            $kredit_da[] = $id_piutang_pendapataan_asset[1];
            $this->mfrm->create_journal_log_account($this->mfrm->get_journal_current(), $id_frm_journal_log, $debit, $debit_da, $kredit, $kredit_da);

        }
        
      }
      if($id_mrp_inventory_payment_booking){
        $this->session->set_flashdata('success', 'Data tersimpan');
      }
      else{
        $this->session->set_flashdata('notice', 'Data tidak tersimpan');
      }
      redirect("mrp/asset/payment-booking/".$pst['id_mrp_inventory_booking']);
    }
    else{
      $this->template->build("asset/add-pay-booking",
        array(
              'url'         => base_url()."themes/".DEFAULTTHEMES."/",
              'menu'        => 'mrp/asset/booking',
            'title'       => lang("mrp_payment_booking")." ".$this->global_models->get_field("mrp_inventory_booking", "title", array("id_mrp_inventory_booking" => $id_mrp_inventory_booking)),
              'detail'      => $detail,
              'id_mrp_inventory_booking'         => $id_mrp_inventory_booking
            ));
      $this->template
        ->set_layout('default')
        ->build("asset/add-pay-booking");
    }
	}
  
  function generate_penyusutan(){
    $kirim = array(
        "mrp_generate_penyusutan_total_asset"   => $this->global_models->get_field("mrp_inventory_department", "count(id_mrp_inventory_department)"),
        "mrp_generate_penyusutan_nomor_asset"   => 0,
        "mrp_generate_penyusutan_account_debit" => array(),
        "mrp_generate_penyusutan_account_kredit"=> array(),
    );
    $this->session->set_userdata($kirim);
    $this->template->build("asset/generate-penyusutan",
      array(
            'url'         => base_url()."themes/".DEFAULTTHEMES."/",
            'menu'        => 'mrp/asset/generate-penyusutan-halaman',
            'title'       => lang("mrp_generate_penyusutan"),
          ));
    $this->template
      ->set_layout('default')
      ->build("asset/generate-penyusutan");
  }
  
  function generate_penyusutan_halaman(){
    $this->template->build("asset/generate-penyusutan-halaman",
      array(
            'url'         => base_url()."themes/".DEFAULTTHEMES."/",
            'menu'        => 'mrp/asset/generate-penyusutan-halaman',
            'title'       => lang("mrp_generate_penyusutan"),
          ));
    $this->template
      ->set_layout('default')
      ->build("asset/generate-penyusutan-halaman");
  }
  
  function batch_generate_penyusutan(){
    $data = $this->global_models->get_query("
      SELECT A.*, B.title AS asset, B.id_mrp_inventory_category
      FROM mrp_inventory_department AS A
      LEFT JOIN mrp_inventory AS B ON A.id_mrp_inventory = B.id_mrp_inventory
      ORDER BY A.id_mrp_inventory_department ASC LIMIT {$this->session->userdata("mrp_generate_penyusutan_nomor_asset")}, 1
      ");
    if($this->session->userdata("mrp_generate_penyusutan_nomor_asset") < 1){
      $nomor = 1;
    }
    else{
      $nomor = $this->session->userdata("mrp_generate_penyusutan_nomor_asset") + 1;
    }
    
//    hitung penusutan bulanan
    $penyusutan = (int)(($data[0]->nilai_awal - $data[0]->nilai_akhir)/$data[0]->umur_ekonomis);
    $nilai_penyusutan_saat_ini = $this->global_models->get_field("mrp_inventory_penyusutan", "sum(nilai)", array("id_mrp_inventory_department" => $data[0]->id_mrp_inventory_department));
    
    $cek_bulan_tahun = $this->global_models->get_field("mrp_inventory_penyusutan", "id_mrp_inventory_penyusutan", array("month" => date("m"), "year" => date("Y")));
    
    if($penyusutan > 0 AND ($data[0]->nilai_awal - $nilai_penyusutan_saat_ini) > $data[0]->nilai_akhir AND !$cek_bulan_tahun){
//    set di penyusutan
      $kirim_penyusutan = array(
          "id_mrp_inventory_department"         => $data[0]->id_mrp_inventory_department,
          "title"                               => "Penyusutan ".date("F Y"),
          "month"                               => date("m"),
          "year"                                => date("Y"),
          "notransaksi"                         => date("Ymd His"),
          "tanggal"                             => date("Y-m-d"),
          "nilai"                               => $penyusutan,
          "create_by_users"                     => $this->session->userdata("id"),
          "create_date"                         => date("Y-m-d H:i:s")
      );
      $id_mrp_inventory_penyusutan = $this->global_models->insert("mrp_inventory_penyusutan", $kirim_penyusutan);
//    set di keuangan
      $kategori = $this->global_models->get("mrp_inventory_category", array("id_mrp_inventory_category" => $data[0]->id_mrp_inventory_category));
      $sesi_account_debit = unserialize($this->session->userdata("mrp_generate_penyusutan_account_debit"));
      $sesi_account_debit[$kategori[0]->id_frm_account_biaya_penyusutan] += $penyusutan;
      
      $sesi_account_kredit = unserialize($this->session->userdata("mrp_generate_penyusutan_account_kredit"));
      $sesi_account_kredit[$kategori[0]->id_frm_account_penyusutan] += $penyusutan;
      
    }
    
    $kirim = array(
        "mrp_generate_penyusutan_nomor_asset"     => $nomor,
        "mrp_generate_penyusutan_account_debit"   => serialize($sesi_account_debit),
        "mrp_generate_penyusutan_account_kredit"  => serialize($sesi_account_kredit),
    );
    $this->session->set_userdata($kirim);
    
    $hasil = array(
            "percent" => ($nomor/$this->session->userdata("mrp_generate_penyusutan_total_asset") * 100),
            "n"       => $nomor,
            "rn"      => $data[0]->sn,
            "note"    => $this->session->userdata("mrp_generate_penyusutan_account_debit")
//            "note"    => $data[0]->asset
        );
      
    print json_encode($hasil);
    die;
  }
  
  function final_generate_penyusutan(){
    $sesi_account_debit = unserialize($this->session->userdata("mrp_generate_penyusutan_account_debit"));

    $sesi_account_kredit = unserialize($this->session->userdata("mrp_generate_penyusutan_account_kredit"));
    $total = 0;
    foreach ($sesi_account_debit AS $id_account => $nilai){
      $debit[] = $nilai;
      $debit_da[] = $id_account;
      $total += $saldo_debit;
    }
    foreach ($sesi_account_kredit AS $id_account => $nilai){
      $kredit[] = $nilai;
      $kredit_da[] = $id_account;
    }
    if($sesi_account_kredit AND $sesi_account_debit){
      $kirim_journal_log = array(
          "id_frm_journal"      => $this->mfrm->get_journal_current(),
          "notransaksi"         => $this->generate_tanggungan_notransaksi(),
          "saldo"               => $total,
          "tanggal"             => date("Y-m-d"),
          "note"                => "Akumulasi Penyusutan Asset ".date("F")." ".date("Y"),
      );

      $id_frm_journal_log = $this->mfrm->create_journal_log($kirim_journal_log);

      if($id_frm_journal_log){
        $this->mfrm->create_journal_log_account($this->mfrm->get_journal_current(), $id_frm_journal_log, $debit, $debit_da, $kredit, $kredit_da);
      }
    }
    die;
  }
  
  function generate_tanggungan_notransaksi(){
    return rand(111111, 999999);
  }
  
}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */